using System;
using System.Collections.Generic;
using System.Text;
using System.Web;

namespace Sedna.Core.Controller.Common
{
    public class CommandArgumentActionParam : IActionParam
    {
        private string name;
        private string cmdArgName;

        /// <summary>
        /// The name that is used to set up the parameter value into the HttpRequest
        /// </summary>
        public string Name
        {
            get { return name; }
            set { name = value; }
        }

        /// <summary>
        /// Parameter name in the CommandArgument string
        /// </summary>
        public string CmdArgName
        {
            set { cmdArgName = value; }
        }

        /// <summary>
        /// Retrieves a value of the parameter from the CommandArgument
        /// </summary>
        /// <param name="executionContext">Used to take the CommandArgument string</param>
        /// <returns>A value of the parameter from the CommandArgument or null if no such parameter is found</returns>
        public string GetValue(IExecutionContext executionContext)
        {
            string value = null;

            if (executionContext.CommandArgument != null)
            {
                // Looking for the start index of CmdArgName in CommandArgument
                int StartIndex = executionContext.CommandArgument.IndexOf(cmdArgName + "=");

                if (StartIndex > -1) // Found
                {
                    // As a result we are pointing at the first index of a value
                    StartIndex += cmdArgName.Length + 1;

                    int Count = executionContext.CommandArgument.IndexOf(";", StartIndex) - StartIndex;

                    value = executionContext.CommandArgument.Substring(StartIndex, Count);
                }                
            }

            return value;
        }
    }
}
